<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
</body>
<script>
var data = [
    {id:1,pid:'',name:'节点1'},
    {id:11,pid:1,name:'节点1-1'},
    {id:12,pid:1,name:'节点1-2'},
    {id:2,pid:'',name:'节点2'},
    {id:21,pid:2,name:'节点2-1'},
    {id:111,pid:11,name:'节点1-1-1'},
]
// 
//方式1.不通过递归
/*
data.forEach(t=>{
    let children = this.data.filter(m=> m.pid === t.id)
    if(children.length>0) t.children = children 
})
// console.log(data)
let result = data.filter(t => t.pid === '')
console.log(result)
*/

//方式2.通过递归,考验能力-脑补
function tranListToTreeData(list, rootValue){
    let arr = []
    list.forEach(t => {
        if(t.pid === rootValue){
            arr.push(t)
            let children = tranListToTreeData(list, t.id)
            if(children.length>0){
                t.children = children
            }
            // console.log('children', children)
        }
        
    });
    return arr
}

let result = tranListToTreeData(data, '')
console.log('result', result)
</script>
</html>